const path = require('path');
const fs = require('fs');

// Read the default config.
const defaultConfigJson = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../conf/config.json'), 'utf8'));

// Read the user config if it exists.
let userConfigJson;
try {
    userConfigJson = JSON.parse(fs.readFileSync(path.resolve('./conf/serve.config.json'), 'utf8'));
} catch (e) {
    userConfigJson = undefined;
    console.log('No user-config.json found. Using default config.');
    console.log('To customize the config, create a ./conf/serve.config.json file in the project root.');
}

// Define the getConfig function.
function getConfig(propertyKey) {
    // Check if the property key is provided.
    if (!propertyKey) {
        throw new Error('No property key provided.');
    }

    // Split the property key by dots.
    const keys = propertyKey.split('.');

    // Get the value from the user config.
    // If the value is not found in the user config, get it from the default config.
    let usingDefaultConfig = false;
    let value;
    if (!userConfigJson) {
        usingDefaultConfig = true;
    } else {
        value = userConfigJson;
        for (const key of keys) {
            if (value[key] === undefined) {
                value = defaultConfigJson;
                usingDefaultConfig = true;
                break;
            }
            value = value[key];
        }
    }

    // If not using default config, return the value.
    if (!usingDefaultConfig) {
        return value;
    }

    // Get the value from the default config and return it.
    value = defaultConfigJson;
    for (const key of keys) {
        value = value[key];
    }
    return value;
}

// Export the getConfig function.
module.exports = {
    getConfig,
};
